package app.services;

import app.enums.GenreCode;
import app.enums.PublicationTypeCode;
import app.models.Book;
import app.models.Genre;
import app.models.PublicationType;
import java.util.ArrayList;
import java.util.List;
import org.javalite.activejdbc.Errors;

/**
 *
 * @author Kseniya Artsiukhova <kartsiukhova@productiveedge.com>
 */
public class BookListServiceImpl implements BookListService {

    @Override
    public List<Book> selectAllBooks() {
        return Book.findAll();
    }

    @Override
    public void deleteBook(Long bookId) {
        Book.deleteBook(bookId);
    }

    @Override
    public void deleteBookList(List<Long> booksId) {
        for (Long id : booksId) {
            Book.deleteBook(id);
        }
    }

    @Override
    public Errors addNewBook(String genreCode, String name, String author, String numberOfPages, String format) {
        Book book = new Book();
        book.setBookAuthor(author);
        book.setBookName(name);
        book.setBookFormat(format);
        Long pages = Long.parseLong(numberOfPages);
        book.setNumberOfPages(pages);

        if (genreCode != null) {
            GenreCode code = GenreCode.getGenreCodeByCode(genreCode);

            if ("none".equals(genreCode)) {
                book.setGenreId(19L);
            } else {
                List<Genre> genres = Genre.find("genre = ?", code.getGenreName());
                book.setGenreId(genres.get(0).getGenreId());
            }
            book.save();
        }
        return book.errors();
    }

    @Override
    public void selectBookById(Long bookId) {
        Book.findById(bookId);
    }

    @Override
    public List<Book> bookListByGenreAndPublicationType(String genre, String publicationType) {
        PublicationTypeCode publicationsTypeCode = PublicationTypeCode.getPublicationsTypeCodeByCode(publicationType);
        GenreCode genreCode = GenreCode.getGenreCodeByCode(genre);
        List<Book> books;

        if (genreCode != null) {
            books = bookListByGenre(genreCode);
        } else {
            books = bookListByPublicationType(publicationsTypeCode);
        }

        return books;
    }

    @Override
    public List<Book> bookListByPublicationType(PublicationTypeCode publicationsTypeCode) {
        PublicationType publicationType = PublicationType.getPublicationTypeByCode(publicationsTypeCode.getTypeName());
        List<Genre> genres = publicationType.getGenres();
        List<Book> books = new ArrayList<Book>();

        for (Genre g : genres) {
            List<Book> subBookList = g.getAll(Book.class);

            if (subBookList != null) {
                if (!subBookList.isEmpty()) {
                    books.addAll(subBookList);
                }
            }
        }

        return books;
    }

    @Override
    public List<Book> bookListByGenre(GenreCode genreCode) {
        List<Book> books = Genre.getGenreByCode(genreCode.getGenreName()).getBookList();
        return books;
    }
}
